﻿using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Xml.Serialization;
using System.IO;
using System.Text;


    public class base64Binary : IXmlSerializable
    {
        private string value;

        public base64Binary() { }

        public base64Binary(string value)
        {
            this.value = value;
        }

        public string Value
        {
            get { return value; }
            set { this.value = value; }
        }

        public static implicit operator string(base64Binary x)
        {
            return x.ToString();
        }

        public static implicit operator base64Binary(string x)
        {
            return new base64Binary(x);
        }

        public override string ToString()
        {
            return value;
        }

        #region IXmlSerializable Members

        public System.Xml.Schema.XmlSchema GetSchema()
        {
            return null;
        }

        public void ReadXml(System.Xml.XmlReader reader)
        {
            MemoryStream ms = null;
            byte[] buffer = new byte[256];
            int bytesRead;

            while ((bytesRead = reader.ReadElementContentAsBase64(buffer, 0, buffer.Length)) > 0)
            {
                if (ms == null)
                    ms = new MemoryStream(bytesRead);

                ms.Write(buffer, 0, bytesRead);
            }

            if (ms != null)
                value = (new UnicodeEncoding()).GetString(ms.ToArray(), 0, ms.ToArray().Length);

        }

        public void WriteXml(System.Xml.XmlWriter writer)
        {
            if (!string.IsNullOrEmpty(value))
            {
                byte[] rawData = System.Text.Encoding.Unicode.GetBytes(value);
                writer.WriteBase64(rawData, 0, rawData.Length);
            }
        }

        public static  string EncodeTo64(string toEncode)
        {
            byte[] toEncodeAsBytes
                  = System.Text.UnicodeEncoding.Unicode.GetBytes(toEncode);
            string returnValue
                  = System.Convert.ToBase64String(toEncodeAsBytes);
            return returnValue;
        }

        public static  string DecodeFrom64(string encodedData)
        {
            byte[] encodedDataAsBytes
                = System.Convert.FromBase64String(encodedData);
            string returnValue = (new UnicodeEncoding()).GetString(encodedDataAsBytes, 0, encodedDataAsBytes.Length);
              // System.Text.UnicodeEncoding.Unicode.GetString(encodedDataAsBytes);
            return returnValue;
        }

        #endregion
    } 


